from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from django.utils.timezone import localtime
from article.utils import Mypage
from question.utils import get_token_user
from .serializers import *


class ActiveViewSet(ModelViewSet):
    queryset = Gathering.objects.all()
    serializer_class = ActiveSerializers
    pagination_class = Mypage

    @action(methods=['post'], detail=True)
    def join(self, request, pk):
        user = get_token_user(request)
        gather = self.get_object()
        if not gather.starttime <= localtime() <= gather.endtime:
            return Response({'success':False, 'message':'不是指定报名时间'})
        gu = gather.users.all().filter(id=user.id)
        if not gu:
            gather.users.add(user)
        else:
            gu.delete()
        return Response({'success': True, 'message': 'OK'})


